import { onMounted } from "vue";
import useInstance from "./useInstance";
import { useLoadingStore } from "@/store/store";

export default function (loadingOptions) {
    const current = useInstance();
    const loading = current.$loading;
    const message = current.$message;

    const loadingStore = useLoadingStore();

    const setLoading = (options = {}) => {
        const { visible, instance } = loadingStore.opereateOptions;
        if (visible === options.visible) {
            console.warn(
                "loading is existing screen, cover now loading status!..."
            );
        }

        if (options.visible) {
            loadingStore.setOperateOption({
                visible: true,
                instance: loading.service({
                    ...loadingOptions,
                    ...options,
                }),
            });
        } else {
            if (!instance)
                return message({
                    type: "error",
                    message: "暂无 loading 实例!",
                });
            instance.close();
            loadingStore.setOperateOption({ visible: false });
        }
    };

    onMounted(() => {
        if (loadingOptions.visible) setLoading(loadingOptions);
    });

    return setLoading;
}
